package cn.edu.zzuli.handler;

import cn.edu.zzuli.entity.R;
import cn.edu.zzuli.util.JwtUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

public class TokenInterceptor implements HandlerInterceptor {

    public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        String token = null;

        //判断请求头有没有token
        if((token = request.getHeader("token")) == null) {
            returnErrorMsg(response, response.getWriter(), R.error().appendMsg("🍪token 呢? 我没看到啊"));
            return false;
        }


        //验证token 是不是我们的token
        if (!JwtUtil.verifyToken(token)) {
            returnErrorMsg(response, response.getWriter(), R.error().appendMsg("🍪token 验证失败，可能过期了吧"));
            return false;
        }


        //把 token 中的 id放到 ThreadLocal 中方便我们后边通过注解获取。
        String idOfToken = JwtUtil.getIdOfToken(token);
        threadLocal.set(Integer.valueOf(idOfToken));
        return true;

    }

    //请求不通过，返回错误信息给客户端
    private void returnErrorMsg(HttpServletResponse response, PrintWriter out, R r) {
        response.setContentType("application/json; charset=utf-8");
        String json = JSONObject.toJSONString(r);
        out.print(json);
        out.flush();
        out.close();
    }
}
